package com.plian.system.listener;

import com.plian.Tools.TokenUtil;
import com.plian.Tools.UuidUtil;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.dao.wf.WfCompletedTaskMapper;
import com.plian.system.service.sys.user.UserService;
import com.plian.system.service.wf.WorkFlowFormService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.task.service.impl.persistence.entity.TaskEntityImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 任务生成监听器
 */
@Slf4j
@Component
public class TaskDeletedListener extends AbstractFlowableEngineEventListener implements FlowableEventListener {
    @Autowired(required = false)
    @Lazy
    private HistoryService historyService;

    @Autowired(required = false)
    @Lazy
    private RuntimeService runtimeService;

    @Autowired(required = false)
    @Lazy
    private TaskService taskService;

    @Autowired
    @Lazy
    private WorkFlowFormService workFlowFormService;

    @Autowired(required = false)
    private WfCompletedTaskMapper wfCompletedTaskMapper;

    @Autowired
    private UserService userService;

    @Override
    @Transactional
    protected void entityDeleted(FlowableEngineEntityEvent event) {
        try {
            assert event != null;
            if (event.getProcessInstanceId()==null) {
                return;
            }
            HistoricProcessInstance historicProcessInstance = historyService
                    .createHistoricProcessInstanceQuery()
                    .processInstanceId(event.getProcessInstanceId())
                    .singleResult();
            String formId = historicProcessInstance.getBusinessKey();
            int formType = (int) runtimeService.getVariable(event.getProcessInstanceId(), "formType");
            List<PageData> formList = workFlowFormService.get(formType, formId, null);
            if (formList.size() != 1) {
                return;
            }
            PageData form = formList.get(0);
            Object entity = event.getEntity();
            if (entity instanceof TaskEntityImpl){
                TaskEntityImpl taskEntity = (TaskEntityImpl) entity;
                PageData pageData = new PageData();
                pageData.put("id", UuidUtil.get32UUID());
                pageData.put("formId", form.get("id"));
                pageData.put("formType", StringUtils.isEmpty(form.getString("form_type"))?form.getString("formType"):form.getString("form_type"));
                pageData.put("formCode", form.get("code"));
                pageData.put("formTitle", form.get("title"));
                pageData.put("applicantId", form.get("applicantId"));
                pageData.put("applicantName", userService.findIdForName(historicProcessInstance.getStartUserId()));
                pageData.put("applyOrganizationId", form.get("applyOrganizationId"));
                pageData.put("applyOrganizationName", form.get("UNITNAME"));
                pageData.put("year", form.get("year"));
                pageData.put("submitTime", historicProcessInstance.getStartTime());
                pageData.put("processInstanceId", historicProcessInstance.getId());
                pageData.put("taskDefinitionKey", taskEntity.getTaskDefinitionKey());
                pageData.put("taskId", taskEntity.getId());
                pageData.put("startTime",taskEntity.getCreateTime());
                pageData.put("finishTime", new Date());
                //pageData.put("duration_millis", taskEntity.getDurationInMillis());
                pageData.put("assigneeId", TokenUtil.getTokenUserId());
                pageData.put("assigneeOrganizationId", TokenUtil.getTokenOrgId());
                pageData.put("operationType", taskService.getTaskComments(taskEntity.getId(),"comment").get(0).getFullMessage());
                pageData.put("remark", form.getString("orgName"));
                wfCompletedTaskMapper.insert(pageData);
            }
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
    }
}
